<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10rem;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="130"
                :model="formValue" style="width: 370rem;" label-align="right">

                <NFormItem label="考核名称:" path="appraiseName">
                  <NInput placeholder="请输入考核名称" v-model:value="formValue.appraiseName" clearable class="commonWidth"
                    :allow-input="noSideSpace" />
                </NFormItem>

                <NFormItem label="选择开始时间:" path="startTime">
                  <DatePicker input-readonly placeholder="请选择选择开始时间" clearable class="commonWidth" type="datetime"
                    v-model:formatted-value="formValue.startTime" @update-formatted-value="handleStartTime" />
                </NFormItem>

                <NFormItem label="选择结束时间:" path="endTime">
                  <DatePicker input-readonly placeholder="请选择选择结束时间" clearable class="commonWidth" type="datetime"
                    v-model:formatted-value="formValue.endTime" :is-date-disabled="disabledEndTime" />
                </NFormItem>

                <NFormItem label="优秀员工人数:" path="excellentNum">
                  <NInput placeholder="请输入优秀员工人数" v-model:value="formValue.excellentNum" clearable class="commonWidth"
                    :allow-input="noSideSpace" />
                </NFormItem>

                <NFormItem label="选择A卷人员:" path="apeopleList">
                  <div style="width: 100%">
                    <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost
                      @click="openScope('apeopleList')">
                      选择人员
                    </NButton>
                    <div class="scope" v-if="formValue.apeopleList?.length">
                      <NScrollbar>
                        <div class="userBox" v-for="(item, index) in formValue.apeopleList" :key="index"
                          :style="{ marginBottom: index == formValue.apeopleList?.length - 1 ? '0px' : '10px' }">
                          <div>{{ item.typeName }}</div>
                          <n-icon @click="handleScope(item.identifyingId, 'apeopleList')" style="cursor: pointer">
                            <CloseFilled />
                          </n-icon>
                        </div>
                      </NScrollbar>
                    </div>
                  </div>
                </NFormItem>

                <NFormItem label="选择B卷人员:" path="bpeopleList">
                  <div style="width: 100%">
                    <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost
                      @click="openScope('bpeopleList')">
                      选择人员
                    </NButton>
                    <div class="scope" v-if="formValue.bpeopleList?.length">
                      <NScrollbar>
                        <div class="userBox" v-for="(item, index) in formValue.bpeopleList" :key="index"
                          :style="{ marginBottom: index == formValue.bpeopleList?.length - 1 ? '0px' : '10px' }">
                          <div>{{ item.typeName }}</div>
                          <n-icon @click="handleScope(item.identifyingId, 'bpeopleList')" style="cursor: pointer">
                            <CloseFilled />
                          </n-icon>
                        </div>
                      </NScrollbar>
                    </div>
                  </div>
                </NFormItem>

                <NFormItem label="选择C卷人员:" path="cpeopleList">
                  <div style="width: 100%">
                    <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost
                      @click="openScope('cpeopleList')">
                      选择人员
                    </NButton>
                    <div class="scope" v-if="formValue.cpeopleList?.length">
                      <NScrollbar>
                        <div class="userBox" v-for="(item, index) in formValue.cpeopleList" :key="index"
                          :style="{ marginBottom: index == formValue.cpeopleList?.length - 1 ? '0px' : '10px' }">
                          <div>{{ item.typeName }}</div>
                          <n-icon @click="handleScope(item.identifyingId, 'cpeopleList')" style="cursor: pointer">
                            <CloseFilled />
                          </n-icon>
                        </div>
                      </NScrollbar>
                    </div>
                  </div>
                </NFormItem>

                <NFormItem label="选择被考核人员:" path="appraisePeopleList">
                  <div style="width: 100%">
                    <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost
                      @click="openScope('appraisePeopleList')">
                      选择人员
                    </NButton>
                    <div class="scope" v-if="formValue.appraisePeopleList?.length">
                      <NScrollbar>
                        <div class="userBox" v-for="(item, index) in formValue.appraisePeopleList" :key="index"
                          :style="{ marginBottom: index == formValue.appraisePeopleList?.length - 1 ? '0px' : '10px' }">
                          <div>{{ item.typeName }}</div>
                          <n-icon @click="handleScope(item.identifyingId, 'appraisePeopleList')" style="cursor: pointer">
                            <CloseFilled />
                          </n-icon>
                        </div>
                      </NScrollbar>
                    </div>
                  </div>
                </NFormItem>

                <NFormItem label="问卷说明:" path="remark">
                  <NInput placeholder="请输入问卷说明" v-model:value="formValue.remark" clearable class="commonWidth"
                    :allow-input="noSideSpace" type="textarea" style="min-height: 100rem" />
                </NFormItem>
                
                <NFormItem label=" " v-if="voteShow">
                  <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost @click="openVotePage">
                    预览投票页面
                  </NButton>
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="width: 120px;background-color: #5faab1" @click="confirm(true)" v-if="workFlowList?.length">
          保存草稿
        </NButton>
        <NButton style="width: 120px;" type="primary" @click="confirm(false)" :loading="loading" v-if="formValue.entityId">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VScope @close="modalVisible = false" @scopeSubmit="getScopeList" :defaultList="defaultList"
      :otherDefaultList="otherDefaultList" />
  </NModal>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentText }}
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import {
  NSpace, NForm, NInput, NFormItem, NButton, NScrollbar, NModal, useMessage,
  NSpin, NIcon, type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'
import { CloseFilled } from '@vicons/material'
import VScope from './AssessScope.vue'
import { subDays } from 'date-fns'
import dayjs from 'dayjs'
import { useViewerStore } from '@/views/OA/Common/store'

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
  title: { type: String, default: () => '新建考核' },
  id: { type: [Number, String], default: () => null },
  flat: { default: () => false }
})
const message = useMessage()
const useStore = useViewerStore()

// 表单数据
const formValue: any = reactive({
  appraiseName: null, //考核名称
  startTime: null, //开始时间
  endTime: null, //结束时间
  excellentNum: null, //优秀员工人数
  remark: null, //问卷说明
  draft: false, //草稿状态
  entityId: null, //流程实体id
  apeopleList: [], //A卷
  bpeopleList: [], //B卷
  cpeopleList: [], //C卷
  appraisePeopleList: [] //选择被考核人员
})
// 规则效验
const rules: any = {
  startTime: {
    required: true,
    message: '请选择开始时间',
    trigger: ['select', 'change']
  },
  endTime: {
    required: true,
    trigger: ['select', 'change'],
    validator: (_: any, value: any) => {
      if (!value || value.length === 0) return new Error('请选择结束时间')
      if(dayjs(formValue.startTime).isAfter(dayjs())) {
        if(!dayjs(value).isAfter(dayjs(formValue.startTime))) {
          return new Error('结束时间必须晚于开始时间')
        }
      } else {
        if(!dayjs(value).isAfter(dayjs())) {
          return new Error('结束时间必须晚于当前时间')
        }
      }
      return true
    }
  },
  apeopleList: {
    required: true,
    type: 'array',
    message: '请选择A卷人员',
    trigger: ['select', 'change']
  },
  bpeopleList: {
    required: true,
    type: 'array',
    message: '请选择B卷人员',
    trigger: ['select', 'change']
  },
  cpeopleList: {
    required: true,
    type: 'array',
    message: '请选择C卷人员',
    trigger: ['select', 'change']
  },
  appraisePeopleList: {
    required: true,
    type: 'array',
    message: '请选择被考核人员',
    trigger: ['select', 'change']
  },
  excellentNum: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入优秀员工人数')
      if (!/^[1-9]\d*$/g.test(value)) return new Error('请输入正整数')
      if (value > 100) return new Error('优秀员工人数不得超过100')
      return true
    }
  },
  appraiseName: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入考核名称')
      if (value?.length > 100) return new Error('考核名称字数不得超过100')
      return true
    }
  },
  remark: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入问卷说明')
      if (value?.length > 500) return new Error('问卷说明字数不得超过500')
      return true
    }
  }
}
// 预览投票页面按钮是否显示 数据全填写时显示
const voteShow = computed(() => {
  let result: any = []
  let flag = null
  Object.keys(formValue).map((it: any) => {
    if (it == 'draft' || it == 'entityId') return result.push(true)
    else if ((it == 'apeopleList' || it == 'bpeopleList' || it == 'cpeopleList' || it == 'appraisePeopleList'))
      return formValue[it].length ? result.push(true) : result.push(false)
    else if (formValue[it]) return result.push(true)
    else return result.push(false)
  })
  flag = result.every((it: any) => it)
  return flag ? true : false
})
// 预览投票页面
const openVotePage = () => {
  useStore.appraisePeopleList = formValue.appraisePeopleList
  useStore.excellentNum = formValue.excellentNum
  useStore.remark = formValue.remark
  useStore.scopeId = null
  useStore.appraiseId = null
  router.push({ name: 'OA/Assess/VoteInfo', params: { appraiseId: 'null' } })
}
// 打开选择人员
const scopeKey = ref()
const defaultList = ref()
const otherDefaultList = ref()
const modalVisible = ref(false)
const openScope = (key: any) => {
  const tmp = ['apeopleList', 'bpeopleList', 'cpeopleList']
  const result: any = []
  tmp.map((it: string) => it != key ? result.push(...formValue[it]) : undefined)
  defaultList.value = formValue[key]
  otherDefaultList.value = key != 'appraisePeopleList' ? result : []
  scopeKey.value = key
  modalVisible.value = true
}
// A/B/C卷/被选择人员删除
const handleScope = (id: any, key: any) => {
  const index = formValue[key].findIndex((it: any) => it.identifyingId == id)
  formValue[key].splice(index, 1)
}
// 人员选择
const getScopeList = (v: any) => {
  formValue[scopeKey.value] = v
  modalVisible.value = false
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 获取流程id
const hint = ref()
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: 'A0558'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  spinShow.value = false
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) router.push({ path: '/OA/Workbench/UserDesktop' })
  else history.back()
}
// 确定
const contentVisible = ref(false)
const contentText = ref('您确定要提交申请吗？')
const formRef = ref<FormInst | null>(null)
const draftFlag = ref<boolean>(false) // 草稿状态
const confirm = (key: boolean) => {
  formRef.value?.validate(async (err) => {
    if (err) return contentVisible.value = false
    contentText.value = key ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    contentVisible.value = true
    draftFlag.value = key
  })
}
// 提交
const loading = ref(false)
const submit = async () => {
  if ((props.id && props.flat) || (!props.id && !props.flat)) {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest({
      module: 'assess',
      api: 'assessSave',
      override: {
        data: {
          ...formValue,
          draft: draftFlag.value
        },
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  } else {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest({
      module: 'assess',
      api: 'assessUpdate',
      override: {
        data: {
          ...formValue,
          id: props.id,
          draft: draftFlag.value
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  }
  goSubmit()
}
// 提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}
// 开始日期选择
const handleStartTime = (v: any) => {
  formValue.startTime = v
  formValue.endTime = null
}
const handleEndTime = (v: any) => {
  if(!formValue.startTime) {
    return formValue.endTime = v
  }
  if(!dayjs(v).isAfter(dayjs(formValue.startTime))) {
    formValue.endTime = null
    return message.warning("")
  }
  formValue.endTime = v
}
// 结束日期禁用
const disabledEndTime = (ts: any) => ts < new Date(subDays(new Date(formValue.startTime?.split(' ')[0]), 1))

// 获取修改详情
const fileList: any = ref([])
const getAssessInfo = async (id: string) => {
  const [error, res] = await sendRequest({
    module: 'assess',
    api: 'assessInfo',
    uri: {
      id
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  Object.keys(formValue).map((it: any) => {
    if (it == 'entityId') return
    if (it == 'excellentNum') return formValue[it] = res.data[it].toString()
    formValue[it] = res.data[it]
  })
}


watch(
  () => route,
  () => {
    if (route.path == '/OA/Assess/AssessAdd' || route.path == '/OA/Assess/AssessUpdate') getWorkFlow()
    if(route.path == '/OA/Assess/AssessUpdate' && props.id) {
      getAssessInfo(String(props.id))
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;

      .scope {
        width: 240rem;
        overflow: hidden;
        height: 120rem;
        background-color: #e1e1e1;
        padding: 10px 15px;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 370rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 26px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 370rem;
  max-width: 800rem;
  padding: 5px 26px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
